<?php namespace App\Http\Controllers\Api;

use App\Files;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\User;
use App\UserAddress;
use App\Userinfo;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Cookie;
use App\VerifyCodeByPhone;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Session;
use Log;

class AuthController extends Controller
{
    public function getUserInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return response()->json(['level'=>'error','message'=>'no_login','data'=>'']);
        }

        $userInfo = Userinfo::whereUserId($user->id)->first();

        if($userInfo){
            $user->userinfo = $userInfo;
        }else{
            $user->userinfo = null;
        }

        $token = CryptoJSAES::encrypt($user->openid,env('AES_KEY'));
        $user->token = $token;

        $userAddress = UserAddress::whereUserId($user->id)->whereIsDefault(1)->first();
        if($userAddress){
            $user->useraddress = $userAddress;
        }else{
            $user->useraddress = null;
        }

        return response()->json(['level'=>'success','message'=>'has_login','data'=>$user]);
    }

    public function wechatLogin(Request $request){
        $state    = $request->get('state');
        $callback = $request->get('callback');

        Log::error("redirturl1==>".$callback);
        if(!is_null($callback)){
            Session::put('redirect_url', $callback);
            Log::error("redirturl2==>".Session::get('redirect_url'));
        }

        $state       = !is_null($state) ? $state : 0;
        $callbackUrl = route('Api.Auth.wechatCallback');
        $url         = WechatLogin::buildRedirectUrl($callbackUrl,$state);
        return redirect($url);
    }

    public function wechatCallback(Request $request){
        $code       = $request->get('code');
        $state      = $request->get('state');

        /** @var  WechatLogin $result */
        $result = WechatLogin::getWechatUserInfo($code);

        $accessToken = $result->getAccessToken();
        $openId      = $result->getOpenId();
        $nickname    = $result->getNickname();
        $sex         = $result->getSex();
        $headImgUrl  = $result->getHeadimgurl();
        $province    = $result->getProvince();
        $city        = $result->getCity();
        $unionid     = $result->getUnionid();

        /** @var  User $userModel */
        $userModel = User::whereOpenid($openId)->first();

        $cookie = null;
        if($userModel){
            $cookie = Cookie::forever("zy_login",$userModel->openid);

        }else{
            $userModel = new User();
            $userModel->openid   = $openId;
            $userModel->password = bcrypt('123456');
            $userModel->reg_ip   = $request->ip();
            $userModel->reg_time = Carbon::now();
            $userModel->save();

            $userInfo = new Userinfo();
            $userInfo->user_id  = $userModel->id;
            $userInfo->nickname = $nickname;
            $userInfo->sex      = $sex;
            $userInfo->province = $province;
            $userInfo->city     = $city;
            $userInfo->save();

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl);
            if($fileModel){
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if(!$imageModel){
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name= 'wechat_img';
                    $imageModel->img_type= $fileModel->file_type;
                    $imageModel->save();

                    $userInfo->photo_id = $imageModel->id;
                    $userInfo->save();
                }
            }
            $cookie = Cookie::forever("zy_login",$userModel->openid);
        }

        $redirectUrl = Session::get('redirect_url');
        if(!is_null($redirectUrl)){
            return redirect($redirectUrl)->cookie($cookie);
        }

        return redirect(route('M.Home.index'))->cookie($cookie);
    }

    public function getCurrentUserId(Guard $guard){
        if($guard->guest())
            return response()->json(['level'=>'error','data'=>'no_login','message'=>'未登录']);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            return response()->json(['level'=>'error','data'=>'no_login','message'=>'用户账号错误']);

        return response()->json(['level'=>'success','message'=>'获取成功','user_id'=>$user->id]);
    }

    /**
     * 获取手机验证码
     *
     * @param GetVerifyCodeByPhoneRequest $request
     *
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws DataException
     * @throws SecurityException
     */
    public function getVerifyCodeByPhone(){

        $phone          = Input::get('phone');
        $isAttact       = VerifyCodeByPhone::whereIp(Input::ip())->orderBy('created_at', 'desc')->first();
        $isAttact_count = VerifyCodeByPhone::whereIp(Input::ip())->count();

        if ($isAttact_count > 3 && $isAttact->created_at->timestamp + 60 > time())
            throw new SecurityException(SecurityException::Wait60Seconds);
        if ($isAttact_count > 24 && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
            throw new SecurityException(SecurityException::NoPermission);

        $result = VerifyCodeByPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            throw new SecurityException(SecurityException::Wait60Seconds);

        VerifyCodeByPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone                 = new VerifyCodeByPhone();
        $VerifyCodeByPhone->phone          = $phone;
        $VerifyCodeByPhone->verify_code    = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip             = \Input::ip();
        $VerifyCodeByPhone->ensure_session = '';

        $sendSms = new YunPian();
        $sendSms->sendBasicSmsWithCode($phone, $VerifyCodeByPhone->verify_code);

        $dataResult = $VerifyCodeByPhone->save();

        return $this->buildResponse(trans('验证码发送成功'));
    }

    public function signUp(){
        /*获取输入*/
        $phone    = Input::get('phone');
        $code     = Input::get('code');
        $password = Input::get('password');

        /** @var VerifyCodeByPhone $verifyCodeByPhone */
        $verifyCodeByPhone = VerifyCodeByPhone::wherePhone($phone)->whereVerifyCode($code)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
            throw new SecurityException(SecurityException::VerifyCodeNotMatch);
        }

        $verifyCodeByPhone -> delete();

        $thatuser = UserManager::signUp(null,null,$phone,$password,0);
        \Auth::login($thatuser,1);

        return $this->buildResponse(trans('注册成功！'));
    }

    public function signOut(Guard $guard){
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $guard->logout();

        return $this->buildResponse(trans('退出登陆成功'));
    }

    public function SignIn(){
        $loginId  = input::get('login_id');
        $username = input::get('username');
        $email    = input::get('email');
        $phone    = input::get('phone');
        $password = input::get('password');

        if($phone){
            $user = UserManager::signInByPhone($phone,$password,1);
        }elseif($email){
            $user = UserManager::signInByEmail($email,$password,1);
        }elseif($username){
            $user = UserManager::signInByUsername($username,$password,1);
        }else{
            if(Tools::isEmail($loginId))
                $user = UserManager::signInByEmail($loginId,$password,1);
            else if(Tools::isPhone($loginId))
                $user = UserManager::signInByPhone($loginId,$password,1);
            else
                $user = UserManager::signInByUsername($loginId,$password,1);
        }

        return $this->buildResponse(trans('登录成功！'),$user);
    }
}